/**
 * 本机页面路由管理
 * 主要做为登陆授权拦截
 * @type {{saveAuthorization?: saveAuthorization, getAuthorization?: (function(): (string|*))|*, saveData?: saveData, getData?: (function(*=): (string|*))|*, saveUserInfo?: saveUserInfo, getUserInfo?: function(): *}}
 */

const store = require("./store.js")
const config = require("./config.js")
const utils = require("../utils/util.js")

function routerAuth(page, isAuth, type) {
    if (isAuth) {
        // 校验授权
        console.log("Jump authentication:" + page)
        if (utils.isInvalid(store.getAuthorization())) {
            let toPath = config.noAuthPage + "?jumpType=navigateTo&nextPage=" + page
            wx.navigateTo({
                url: toPath,
                success: function (res) {
                    // 通过eventChannel向被打开页面传送数据
                    res.eventChannel.emit('acceptDataFromOpenerPage', utils.getUrlParams(page))
                }
            })
            return;
        }
    }
    // swich 切换 就是tab栏
    if (type == "tab") {
        wx.switchTab({
            url: page + ((page.indexOf("?")>0?'&':'?')+"jumpType=switchTab"),
            success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                try {
                    res.eventChannel.emit('acceptDataFromOpenerPage', utils.getUrlParams(page))
                } catch (e) {
                }
            }
        })
    } else if (type == "rTo") {
        // 重定向
        wx.redirectTo({
            url: page + ((page.indexOf("?")>0?'&':'?')+"jumpType=redirectTo"),
            fail: function (res) {
                wx.switchTab({
                    url: page + "?jumpType=switchTab",
                })
            },
            success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                try {
                    res.eventChannel.emit('acceptDataFromOpenerPage', utils.getUrlParams(page))
                } catch (e) {
                }
            }
        })
    } else if ("nTo") {
        wx.navigateTo({
            url: page + ((page.indexOf("?")>0?'&':'?')+"jumpType=navigateTo"),
            fail: function (res) {
                wx.switchTab({
                    url: page + "?jumpType=switchTab",
                })
            },
            success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', utils.getUrlParams(page))
            }
        })
    } else {
        wx.reLaunch({
            url: page + "?jumpType=reLaunch",
            fail: function (res) {
                wx.switchTab({
                    url: page + "?jumpType=switchTab",
                })
            }
            , success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', utils.getUrlParams(page))
            }
        })
    }
}

module.exports = {
    routerAuth
}
